package com.ruoyi.dynamic.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dynamic.domain.UserDynamicAuto;
import com.ruoyi.dynamic.domain.UserParty;
import com.ruoyi.dynamic.mapper.UserDynamicAutoMapper;
import com.ruoyi.dynamic.service.IUserPartyService;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.service.IPriceSettingService;

/**
 * 用户派对Controller
 * 
 * @author DEREK
 * @date 2023-12-05
 */
@RestController
@RequestMapping("/dynamic/party")
public class UserPartyController extends BaseController
{
    @Autowired
    private IUserPartyService userPartyService;
    @Autowired
    private IPriceSettingService priceSettingService;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 查询用户派对列表
     */
    @PreAuthorize("@ss.hasPermi('dynamic:party:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserParty userParty)
    {
        startPage();
        List<UserParty> list = userPartyService.selectUserPartyList(userParty);
        return getDataTable(list);
    }

    /**
     * 导出用户派对列表
     */
    @PreAuthorize("@ss.hasPermi('dynamic:party:export')")
    @Log(title = "用户派对", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserParty userParty)
    {
        List<UserParty> list = userPartyService.selectUserPartyList(userParty);
        ExcelUtil<UserParty> util = new ExcelUtil<UserParty>(UserParty.class);
        util.exportExcel(response, list, "用户派对数据");
    }

    /**
     * 获取用户派对详细信息
     */
    @PreAuthorize("@ss.hasPermi('dynamic:party:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
    	UserParty byId = userPartyService.getById(id);
    	if(StringUtils.isNotEmpty(byId.getImg())) {
    		String[] split = byId.getImg().split(",");
    		byId.setSimpleSpectrum1(Arrays.asList(split));
    	}
        return AjaxResult.success(byId);
    }

    /**
     * 新增用户派对
     */
    @PreAuthorize("@ss.hasPermi('dynamic:party:add')")
    @Log(title = "用户派对", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserParty userParty)
    {
    	if(StringUtils.isNotEmpty(userParty.getPartyTheme())) {
    		PriceSetting one = priceSettingService.getOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "约玩类型")
    				.eq(PriceSetting::getPriceName, userParty.getPartyTheme()));
    		if(null != one) {
    			userParty.setPartyInterest(one.getRemark());
    		}
    	}
//    	if(userParty.getRegular() > 0) {
//    		String key = userParty.getId()+"-2-"+userParty.getRegular();
//    		Date pastDateTime = DateUtils.getPastDateTime(userParty.getRegular(), userParty.getCreateTime(), 2);
//    		long expireTime = DateUtils.getDaySecond(userParty.getCreateTime(), pastDateTime);
//    		redisUtil.set(key, key, expireTime);
//    	}
        return toAjax(userPartyService.save(userParty));
    }

    /**
     * 修改用户派对
     */
    @PreAuthorize("@ss.hasPermi('dynamic:party:edit')")
    @Log(title = "用户派对", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserParty userParty)
    {
    	UserParty party = userPartyService.getOne(new LambdaQueryWrapper<UserParty>().eq(UserParty::getId, userParty.getId())
    			.select(UserParty::getId,UserParty::getRegular));
    	if(null == party) {
    		return AjaxResult.error("约玩不存在");
    	}
    	userParty.setRemarks("后台更改，更新最新时间"+DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",需要修改的状态："+userParty.getStatus());
    	userParty.setCreateTime(new Date());
//    	// 删除定时
//		String delKey = userParty.getId()+"-2-"+party.getRegular();
//		if(redisUtil.hasKey(delKey)) {
//			redisUtil.del(delKey);
//		}
//    	if(userParty.getRegular() > 0) {
//    		String key = userParty.getId()+"-2-"+userParty.getRegular();
//    		Date pastDateTime = DateUtils.getPastDateTime(userParty.getRegular(), userParty.getCreateTime(), 2);
//    		long expireTime = DateUtils.getDaySecond(userParty.getCreateTime(), pastDateTime);
//    		redisUtil.set(key, key, expireTime);
//    	}
        return toAjax(userPartyService.updateById(userParty));
    }

    /**
     * 删除用户派对
     */
    @PreAuthorize("@ss.hasPermi('dynamic:party:remove')")
    @Log(title = "用户派对", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userPartyService.deleteUserPartyByIds(ids));
    }
    
    @Autowired
    private UserDynamicAutoMapper userDynamicAutoMapper;
    
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:edit')")
	 @Log(title = "将派对加入自动发布列表", businessType = BusinessType.UPDATE)
	 @GetMapping("/joinPartyAuto")
	 public AjaxResult joinPartyAuto(Long partyId,Long userId)
	 {
    	UserDynamicAuto auto = userDynamicAutoMapper.selectOne(new LambdaQueryWrapper<UserDynamicAuto>()
    			.eq(UserDynamicAuto::getUserId, userId)
    			.eq(UserDynamicAuto::getType, 2).last("limit 1"));
    	if(null != auto) {
    		if(auto.getObjId().contains(partyId.toString())) {
    			return AjaxResult.error("当前派对已经加入动态库");
    		}else {
    			if(StringUtils.isNotEmpty(auto.getObjId())) {
    				auto.setObjId(auto.getObjId()+","+partyId);
    			}else {
    				auto.setObjId(String.valueOf(partyId));
    			}
    		}
    		userDynamicAutoMapper.updateById(auto);
    	}else {
    		auto = new UserDynamicAuto();
    		auto.setUserId(userId);
    		auto.setObjId(partyId.toString());
    		auto.setType(2);
    		auto.setTime(DateUtils.stringToDate("2024-08-12 19:53:33", "yyyy-MM-dd HH:mm:ss"));
    		userDynamicAutoMapper.insert(auto);
    	}
    	String key = "party_auto0812";
    	redisUtil.set(key, auto.getObjId());
    	String timeKey = "party_auto_time";
    	redisUtil.set(timeKey, DateUtils.dateToString(auto.getTime(), "yyyy-MM-dd HH:mm:ss"));
    	UserParty party = new UserParty();
    	party.setIsAutomatic(1);
    	party.setId(partyId);
    	userPartyService.updateById(party);
		return AjaxResult.success(); 
	 }
}
